import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { login, register, getProfile, wechatLogin, checkWeChatStatus } from '@/api/auth'
import type { LoginForm, RegisterForm, User } from '@/types/auth'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const loading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const userInfo = computed(() => user.value)

  // 传统登录
  const loginUser = async (loginForm: LoginForm) => {
    try {
      loading.value = true
      const response = await login(loginForm)
      
      if (response.data.success && response.data.data) {
        token.value = response.data.data.token
        user.value = response.data.data.user
        
        // 保存到本地存储
        localStorage.setItem('token', token.value)
        
        ElMessage.success('登录成功')
        return { success: true }
      } else {
        ElMessage.error(response.data.message)
        return { success: false, message: response.data.message }
      }
    } catch (error: any) {
      ElMessage.error(error.message || '登录失败')
      return { success: false, message: error.message || '登录失败' }
    } finally {
      loading.value = false
    }
  }

  // 用户注册
  const registerUser = async (registerForm: RegisterForm) => {
    try {
      loading.value = true
      const response = await register(registerForm)
      
      if (response.data.success) {
        ElMessage.success('注册成功')
        return { success: true }
      } else {
        ElMessage.error(response.data.message)
        return { success: false, message: response.data.message }
      }
    } catch (error: any) {
      ElMessage.error(error.message || '注册失败')
      return { success: false, message: error.message || '注册失败' }
    } finally {
      loading.value = false
    }
  }

  // 微信扫码登录
  const loginWithWeChat = async () => {
    try {
      loading.value = true
      const response = await wechatLogin()
      
      if (response.data.success && response.data.data) {
        return {
          success: true,
          qrCode: response.data.data.qrCode,
          state: response.data.data.state
        }
      } else {
        ElMessage.error(response.data.message)
        return { success: false, message: response.data.message }
      }
    } catch (error: any) {
      ElMessage.error(error.message || '微信登录失败')
      return { success: false, message: error.message || '微信登录失败' }
    } finally {
      loading.value = false
    }
  }

  // 检查微信登录状态
  const checkWeChatLoginStatus = async (state: string) => {
    try {
      const response = await checkWeChatStatus(state)
      return response.data
    } catch (error: any) {
      return { success: false, message: error.message || '检查状态失败' }
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      if (!token.value) return { success: false }
      
      const response = await getProfile()
      
      if (response.data.success && response.data.data) {
        user.value = response.data.data.user
        return { success: true }
      } else {
        // Token 可能已过期
        logout()
        return { success: false }
      }
    } catch (error: any) {
      logout()
      return { success: false }
    }
  }

  // 登出
  const logout = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
    ElMessage.success('已退出登录')
  }

  // 初始化（检查本地存储的 token）
  const init = async () => {
    if (token.value) {
      await fetchUserInfo()
    }
  }

  return {
    // 状态
    user,
    token,
    loading,
    
    // 计算属性
    isAuthenticated,
    userInfo,
    
    // 方法
    loginUser,
    registerUser,
    loginWithWeChat,
    checkWeChatLoginStatus,
    fetchUserInfo,
    logout,
    init
  }
})
